package com.store.bookstore_backend.service.impl;

import com.store.bookstore_backend.domain.Categories;
import com.store.bookstore_backend.mapper.CategoriesMapper;
import com.store.bookstore_backend.service.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoriesServiceImpl implements CategoriesService {
    @Autowired
    CategoriesMapper categoriesMapper;

    private List<Categories> buildCategoryTree(List<Categories> allCategories) {
        List<Categories> rootCategories = new ArrayList<>();

        // 建立一个ID到分类的映射
        Map<Integer, Categories> categoryMap = new HashMap<>();
        for (Categories category : allCategories) {
            categoryMap.put(category.getId(), category);
        }

        // 遍历所有分类，构建父子关系
        for (Categories category : allCategories) {
            if (category.getParentId() == null) {
                // 如果没有父节点，则是根分类
                rootCategories.add(category);
            } else {
                // 有父节点，加入到父分类的 children 中
                Categories parentCategory = categoryMap.get(category.getParentId());
                if (parentCategory != null) {
                    parentCategory.getChildren().add(category);
                }
            }
        }

        return rootCategories;
    }

    @Override
    public List<Categories> getAllCategories() {
        // 查询所有分类
        List<Categories> allCategories = categoriesMapper.selectAllCategories();

        // 构建嵌套结构

        return buildCategoryTree(allCategories);
    }
}
